<template>
	<view class="login-wrap">
		<!-- <u--image src="/static/logo.png" width="80px" height="80px" @click="click" shape="circle"></u--image> -->
		<div class="text">立即登录</div>
		<!-- <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号授权</button> -->
		<u-button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"color="#21B579" shape="circle" type="primary" text="手机号授权登录"></u-button>
	</view>
</template>

<script>
export default {
	data() {
		return {
			openId: '',
			userInfo: {},
			userId: ''
		};
	},
	onLoad() {
		this.getOpenID();
	},
	methods: {
		// 获取openid
		getOpenID() {
			let that = this;
			uni.login({
				provider: 'weixin', //使用微信登录
				success: function (loginRes) {
					console.log(loginRes);
					that.$api.post('/fit/getOpenId', { jscode: loginRes.code }).then((res) => {
						console.log(res, '获取openid');
						that.openId = res.data.openId;
						that.login(res.data.openId);
						//静默注册
						that.$api.post('/fit/regUser', { openid: res.data.openId }).then((response) => {
							console.log(response, '静默注册');
						});
					});
				}
			});
		},
		getPhoneNumber(e) {
			let that = this;
			// console.log(this)
			// console.log(that.openId,'klfjjdsfjkdfsjkfdsjksdfdfjskjk')
			if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
				console.log('用户拒绝提供手机号');
			} else {
				// console.log('用户同意提供手机号');
				uni.login({
					provider: 'weixin',
					success({ errMsg, code }) {
						if (errMsg == 'login:ok') {
							// console.log(e);
							// console.log(code);
							// 解析手机号码【3】
							that.$api.post('/fit/getPhoneNumber', { jscode: e.detail.code }).then((res) => {
								console.log(res, '解析手机号码');
								// 绑定手机号
								that.$api.post('/fit/bindPhone', { openid: that.openId, phone: res.data.phoneNumber }).then((res) => {
									console.log(res, '绑定手机号');
									that.login(that.openId);
								});
							});
						}
					}
				});
			}
		},
		// 登录
		login(openId) {
			this.$api.post('/fit/login', { openid: openId || that.data.openId }).then((res) => {
				console.log(res, '登录');
				this.userId = res.data.id;
				getApp().globalData.userInfo = res.data
				uni.setStorage({
					key: 'userInfo',
					data: res.data,
					success: function () {
						console.log('success');
						uni.switchTab({
							url: '../index/index'
						});
					}
				});
			});
		}
	}
};
</script>

<style lang="scss">
.login-wrap {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	background-color: #F7F7F8;
	margin: 0 auto;
	display: flex;
	justify-content: flex-start;
	align-items: center;
	flex-direction: column;
	padding: 60rpx;
	padding-top: 300rpx;
	// background: url('/static/bg.jpeg') no-repeat;
	// background-size: cover;
	.text{
		color: #333;
		font-size: 44rpx;
		font-weight: bold;
		margin-bottom: 140rpx;
	}
	.submit {
		width: 40%;
		margin-top: 80rpx;
	}
}
</style>
